//
//  FDSendVerifyCodeButton.m
//  FD
//
//  Created by xiaofang wang on 2019/1/5.
//  Copyright © 2019年 ZhiYuan Network. All rights reserved.
//  发送验证码按钮

#import "FDSendVerifyCodeButton.h"
@interface FDSendVerifyCodeButton()
/**定时器*/
@property (nonatomic, strong) NSTimer *verifycodeTimer;
/**计数器*/
@property (nonatomic) NSInteger count;
@end

@implementation FDSendVerifyCodeButton

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if (self) {
        NSString *sendCodeStr = NSLocalizedString(SendCode, nil); //发送验证码
        self.titleLabel.attributedText = [self getSendCodeAttributeStringWithString:sendCodeStr];
    }
    return self;
}

#pragma mark - 接口
- (void)verifyCodeCountDownTime:(NSInteger)timeCount {
    
    self.count = timeCount;
    
    //间隔:1s 重复:YES
    self.verifycodeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
}

#pragma mark - private
- (void)countDownAction {
    if (self.count < 1) {
        self.enabled = YES; //
        [self.verifycodeTimer invalidate]; //1.关闭定时器
        //2.修改按钮文字：@“发送验证码”
        NSString *sendCodeStr = NSLocalizedString(SendCode, nil); //发送验证码
        self.titleLabel.attributedText = [self getSendCodeAttributeStringWithString:sendCodeStr];
    }else {
        self.enabled = NO; //倒计时过程中禁用按钮
        NSString *chongFaStr = @"Repend";
        if ([NSString rb_ChineseLanguage]) {
            chongFaStr = @"重发";
        }
        NSString *downStr = [NSString stringWithFormat:@"%@(%lds)",chongFaStr,self.count];
        self.titleLabel.attributedText = [self getSendCodeAttributeStringWithString:downStr];
    }
    self.count--;
}



- (NSMutableAttributedString *)getSendCodeAttributeStringWithString:(NSString *)str {
    //富文本验证码倒计时
    //按钮也是可以使用富文本的
    [self setTitle:str forState:(UIControlStateNormal)];
    [self setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    NSDictionary *attDic = @{NSForegroundColorAttributeName:[UIColor redColor],
                             NSFontAttributeName:[UIFont systemFontOfSize:16.0],
                             NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)
                             };
    
//    self.backgroundColor = [UIColor lightGrayColor]; //1-5
    NSMutableAttributedString *attstrM = [[NSMutableAttributedString alloc] initWithString:str attributes:attDic];
    return attstrM;
}
@end
